package com.hust.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class ArrayTypeHandler extends BaseTypeHandler<List> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List parameter,
                                    JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public List getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        return JSON.parseArray(rs.getString(columnName), JSONReader.Feature.UseBigDecimalForDoubles);
    }

    @Override
    public List getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return JSON.parseArray(rs.getString(columnIndex), JSONReader.Feature.UseBigDecimalForDoubles);
    }

    @Override
    public List getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        return JSON.parseArray(cs.getString(columnIndex), JSONReader.Feature.UseBigDecimalForDoubles);
    }
}